export * from './ant-component'
export * from './page'
export * from './regex'
export * from './SM'
export * from './SSE'

// 截取名称，中文名字截取后两个字，英文名字截取前两个字母
export function getShortName(name = '', length = 2) {
  return name.substring(name.length - length)
}

export const replaceEmptyStr = (val: any) => {
  return [null, undefined, ''].includes(val) ? '/' : val
}

// 根据图片地址生成对应缩略图地址
export const customImgUrl = (url: string, width: number, height: number) => {
  return `/p-img/${width}x${height}${url}`
}

// 替换URL参数
export const replaceUrlParam = (url: string, key: string, value: string) => {
  if (url.indexOf(key) > -1) {
    const reg = new RegExp(`((?=${key}=).*?(?=&))|((?=${key}=).*)`)
    url = url.replace(reg, `${key}=${value}`)
  } else {
    const join = url.indexOf('?') > -1 ? '&' : '?'
    url += `${join}${key}=${value}`
  }
  return url
}

import { message } from 'ant-design-vue'
import { uuid } from 'g6-fn'

import manualMessage from '@/components/ManualMessage'
interface Item {
  value: string | number
  name: string
  [key: string]: any
}
export function filterArrayByValue(value: string | number, array: Item[]): Item | null {
  const filteredItems = array.filter(item => item.value === value)
  return filteredItems.length > 0 ? filteredItems[0] : null
}

//  判断文件格式是否有效
export const hasValidExtension = (fileName: string, validExtensions: string[]) => {
  const fileExtension = fileName.split('.').pop()?.toLowerCase()
  if (!fileExtension) {
    return false
  }
  return validExtensions.includes('.' + fileExtension)
}

// 获取元素的距离顶部的距离
export const getDistanceFromTop = (element: HTMLElement | null | undefined) => {
  let distance = 0
  while (element) {
    distance += element.offsetTop
    element = element.offsetParent as HTMLElement
  }
  return distance
}

interface WaitLoadingConfig {
  loadingText?: string
  successText?: string
  errorText?: string
}
const defaultConfig: WaitLoadingConfig = {
  loadingText: '数据准备中,请耐心等待...',
  successText: '开始下载',
  errorText: '下载失败'
}

// 等待Promise处理loading
export const waitLoading = async <T>(
  promise: Promise<ResponseData<string>>,
  config: Partial<WaitLoadingConfig> = {}
): Promise<undefined | T | ResponseData<string>> => {
  const key = uuid()
  const { loadingText, successText, errorText } = { ...defaultConfig, ...config }
  let res
  // debugger
  try {
    manualMessage.loading(loadingText, 0, undefined, key)
    res = await promise
    manualMessage.destroy()
    message.success({ content: successText, key })
  } catch (error: any) {
    manualMessage.destroy()
    message.error({ content: error.message || errorText, key })
  }
  return res
}

// 字符串省略
export const lineClamp = (str: string, maxLength = 5) => {
  return str.length > maxLength ? str.slice(0, maxLength) + '...' : str
}

// 在执行函数之前，先执行一个函数
export const beforeCallFunction = (fn: Function, beforeFn: Function) => {
  return (...args: any[]) => {
    beforeFn()
    return fn(...args)
  }
}

// 获取文件夹名称
export const getFolderName = (path: string) => {
  if (!path) {
    return ''
  }
  const arr = path.split('/')
  return arr[0]
}

// 获取文件后缀
export const getFileType = (str: string) => {
  const strArr = str.split('.')
  return strArr.length < 2 ? '' : strArr.at(-1)?.toLocaleLowerCase()
}

//获取文件类型
export const getFileMediaType = (fileName: string): string => {
  const fileExtension = fileName.split('.').pop()?.toLowerCase()
  if (fileExtension) {
    switch (fileExtension) {
      case 'txt':
      case 'json':
        return 'text'
      case 'jpg':
      case 'jpeg':
      case 'png':
        return 'image'
      case 'mp4':
      case 'mov':
      case 'avi':
      case 'mkv':
      case 'flv':
        return 'video'
      default:
        return 'Unknown'
    }
  }
  return 'Unknown'
}

// 拼接两个时间
export const spliceTwoTimes = (time1: string, time2: string) => {
  if (time1 || time2) {
    return `${time1 || ''}~${time2 || ''}`
  }
  return '/'
}

// 计算字符的字节数
export const countStrToBit = (str: string) => {
  const encoder = new TextEncoder()
  const bytes = encoder.encode(str)
  return bytes.length
}

// 根据下载地址下载文件
export const downloadFile = (url: string, fileName?: string) => {
  const a = document.createElement('a')
  a.href = url
  a.download = fileName || ''
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

// 传入俩个数组，返回俩个数组的差集
export const getDifference = (arr1: any[], arr2: any[]) => {
  return arr1.filter(item => !arr2.includes(item))
}

// 验证一个URL是否包含图片类型
export const isImage = (url: string) => {
  const reg = /\.(png|jpg|jpeg|gif|svg|webp|ico|bmp|tiff)(\?.*)?$/i
  return reg.test(url)
}
// 验证一个URL是否包含json类型
export const isJson = (url: string) => {
  const reg = /\.(json)(\?.*)?$/i
  return reg.test(url)
}
// 验证一个URL是否包含文本类型
export const isText = (url: string) => {
  const reg = /\.(doc|docx|rtf|xml|txt|pdf)(\?.*)?$/i
  return reg.test(url)
}
// 验证一个URL是否包含json类型
export const isVideo = (url: string) => {
  const reg = /\.(mp4|rmvb|mkv|avi)(\?.*)?$/i
  return reg.test(url)
}
// 验证一个URL是否包含pdf,doc,excel类型
export const isOffice = (url: string) => {
  const reg = /\.(doc|docx|xls|xlsx|ppt|pptx|pdf)(\?.*)?$/i
  return reg.test(url)
}

// 验证一个URL是不是包含zip类型
export const isZip = (url: string) => {
  const reg = /\.(zip|rar|7z|tar|gz)(\?.*)?$/i
  return reg.test(url)
}

// 复制字符串
export const copyText = (text: string) => {
  const input = document.createElement('input')
  input.value = text
  document.body.appendChild(input)
  input.select()
  document.execCommand('copy')
  document.body.removeChild(input)
}

/**
 * 将RGB或者RGBA转换为16进制
 */
export const rgbToHex = (color: string) => {
  // 判断是否是rgb或者rgba
  if (!/^(rgb|rgba)/.test(color)) {
    return color
  }

  const reg = /rgba?\((\d+),\s*(\d+),\s*(\d+)(,\s*(\d+))?\)/
  const result = color.match(reg)
  if (!result) {
    return ''
  }
  const [, r, g, b] = result
  return `#${(+r).toString(16)}${(+g).toString(16)}${(+b).toString(16)}`.toUpperCase()
}

/**
 * 将16进制颜色转换为RGB或者RGBA
 */
export const hexToRgb = (color = '#1868E9', opacity = 1) => {
  if (!/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(color)) {
    return color
  }
  let hex = color.slice(1)
  if (hex.length === 3) {
    hex = hex
      .split('')
      .map(item => item + item)
      .join('')
  }
  const r = parseInt(hex.slice(0, 2), 16)
  const g = parseInt(hex.slice(2, 4), 16)
  const b = parseInt(hex.slice(4, 6), 16)
  return `rgba(${r},${g},${b},${opacity})`
}
